package jp.reflexworks.gae.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.appengine.api.datastore.KeyRange;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;

public class AllocateIdsUtil {
	
	public long[] getAllocateIds(String kind, long num) {
		return getAllocateIds(null, kind, num);
	}
		
	public long[] getAllocateIds(DatastoreService datastore, String kind, long num) {
		if (datastore == null) {
			datastore = DatastoreServiceFactory.getDatastoreService();
		}
		KeyRange keys = datastore.allocateIds(kind, num);
		List<Long> ids = new ArrayList<Long>();
		if (keys != null) {
			Iterator<com.google.appengine.api.datastore.Key> it = keys.iterator();
			while (it.hasNext()) {
				com.google.appengine.api.datastore.Key key = it.next();
				ids.add(key.getId());
			}
		}
		
		int size = ids.size();
		if (size == 0) {
			return null;
		}
		long[] ret = new long[size];
		for (int i = 0; i < size; i++) {
			ret[i] = ids.get(i);
		}
		return ret;
	}

}
